﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace lottery.admin.Models
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            this.AddRange(items);
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }
    }

    public static class PaginatedExtend
    {
        public static async Task<PaginatedList<TResult>> CreatePaginated<TResult>(this IQueryable<TResult> source, int pageIndex, int pageSize)
        {
            //var count = await source.CountAsync(); // for performance
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

            return new PaginatedList<TResult>(items, 300000, pageIndex, pageSize);
        }

        public static async Task<PaginatedList<TResult>> CreatePaginated<TSource, TResult>(this IQueryable<TSource> source, Func<TSource, TResult> selector, int pageIndex, int pageSize)
        {
            //var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            List<TResult> result = items.Select(selector).ToList();

            return new PaginatedList<TResult>(result, 300000, pageIndex, pageSize);
        }
    }
}
